package com.cyl.manager.act.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.cyl.h5.config.SecurityUtil;
import com.cyl.manager.act.convert.CouponCategoryConvert;
import com.cyl.manager.act.domain.entity.CouponCategory;
import com.cyl.manager.act.domain.entity.MemberCoupon;
import com.cyl.manager.act.domain.query.CouponActivitySy;
import com.cyl.manager.act.domain.query.MemberCouponQuery;
import com.cyl.manager.act.domain.vo.MemberCouponVO;
import com.cyl.manager.act.mapper.CouponCategoryMapper;
import com.cyl.manager.act.mapper.MemberCouponMapper;
import com.cyl.manager.act.pojo.dto.CouponCategoryDTO;
import com.cyl.manager.act.pojo.query.CouponCategoryByDpQuery;
import com.cyl.manager.act.pojo.vo.CouponCategoryByDpVO;
import com.cyl.manager.act.pojo.vo.CouponCategoryVO;
import com.cyl.manager.pms.domain.entity.Product;
import com.cyl.manager.pms.domain.vo.DyFlq;
import com.cyl.manager.pms.domain.vo.DyFlqSy;
import com.cyl.manager.ums.domain.entity.Member;
import com.cyl.manager.ums.mapper.MemberMapper;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.github.pagehelper.PageHelper;
import com.ruoyi.common.annotation.Excel;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.config.LocalDataUtil;

import io.swagger.annotations.ApiModelProperty;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 用户领券记录Service业务层处理
 *
 * @author zcc
 */
@Service
public class MemberCouponService {
    @Autowired
    private MemberCouponMapper memberCouponMapper;
    @Autowired
    private MemberMapper memberMapper;
    @Autowired
    private CouponCategoryMapper couponCategoryMapper;
    @Autowired
    private CouponCategoryConvert couponCategoryConvert;
    @Autowired
    private CouponCategoryService couponCategoryService;
    
    /**
     * 查询用户领券记录
     *
     * @param id 用户领券记录主键
     * @return 用户领券记录
     */
    public MemberCoupon selectById(Long id) {
        return memberCouponMapper.selectById(id);
    }

    public MemberCoupon selectValidCoupon(Long id) {
        MemberCoupon coupon = memberCouponMapper.selectById(id);
        if (coupon == null) {
            return null;
        }
        if (Objects.equals(coupon.getUseStatus(), 1)) {
            throw new RuntimeException("优惠券已使用");
        }
        LocalDateTime now = LocalDateTime.now();
        if (coupon.getBeginTime().isAfter(now)) {
            throw new RuntimeException("优惠券未到开始使用日期");
        }
        if (coupon.getEndTime().isBefore(now)) {
            throw new RuntimeException("优惠券已过期");
        }
        return coupon;
    }

//    /** 名称 */
//    @Excel(name = "名称")
//    private String title;
//   /** 描述 */
//    @Excel(name = "描述")
//    private String ms;
//    
//    @ApiModelProperty("店铺部门id")
//    @Excel(name = "店铺部门id")
//    private Long deptDpId;
//    
//    @ApiModelProperty("店铺部门名称")
//    @Excel(name = "店铺部门名称")
//    private String deptDpName;
//    
//    @ApiModelProperty("已核销数量")
//    @Excel(name = "已核销数量")
//    private Integer hxsl;
    
    /**
     * 查询导出
     * @param query
     * @return
     */
    public List<CouponCategoryByDpVO> exportByDp(CouponCategoryByDpQuery query) {
        String title = "";
        String ms = "";
    	CouponCategory couponCategory = couponCategoryService.selectCheckById(Long.parseLong(query.getCategoryId()));
    	if(couponCategory!=null) {
    		title = couponCategory.getTitle();
    		ms = couponCategory.getMs();
    	}
        QueryWrapper<MemberCoupon> qw = new QueryWrapper<>();
        qw.eq("coupon_category_id", query.getCategoryId());
        qw.eq("use_status", 1);
        qw.ge("use_time", query.getStartTime());
        qw.le("use_time", query.getEndTime());
        qw.select("dept_dp_id , count(*) use_status");
        qw.groupBy("dept_dp_id");
        List<CouponCategoryByDpVO>  retList = new ArrayList<CouponCategoryByDpVO>();
        List<MemberCoupon> list = memberCouponMapper.selectList(qw);
        if(list!=null) {
        	for (MemberCoupon memberCoupon : list) {
        		CouponCategoryByDpVO vo = new CouponCategoryByDpVO();
        		vo.setTitle(title);
        		vo.setMs(ms);
        		vo.setDeptDpId(memberCoupon.getDeptDpId());
        		vo.setHxsl(memberCoupon.getUseStatus());
			}
        }
        return retList;
    }
    
    
    /**
     * 查询用户领券记录列表
     *
     * @param query 查询条件
     * @param page  分页条件
     * @return 用户领券记录
     */
    public Page<MemberCouponVO> selectList(MemberCouponQuery query, Pageable page) {

        PageHelper.startPage(page.getPageNumber() + 1, page.getPageSize());
        QueryWrapper<MemberCoupon> qw = new QueryWrapper<>();
        Long qrDeptZbjId = query.getDeptZbjId();
        if(qrDeptZbjId!=null) {
            qw.eq("dept_zbj_id", qrDeptZbjId);
        }
        Long couponActivityId = query.getCouponActivityId();
        if (couponActivityId != null) {
            qw.eq("coupon_activity_id", couponActivityId);
        }
        Long memberId = query.getMemberId();
        if (memberId != null) {
            qw.eq("member_id", memberId);
        }
        Integer useStatus = query.getUseStatus();
        if (useStatus != null) {
            qw.eq("use_status", useStatus);
        }
        
        LocalDateTime endTimeGe = query.getEndTimeGe();
        if(endTimeGe!=null) {
        	qw.ge("end_time", endTimeGe);
        }
        
        LocalDateTime endTimeLe = query.getEndTimeLe();
        if(endTimeLe!=null) {
        	qw.le("end_time", endTimeLe);
        }
        
        
        List<MemberCoupon> list = memberCouponMapper.selectList(qw);

        long total = ((com.github.pagehelper.Page) list).getTotal();
        if (total < 1) {
            return new PageImpl<>(Collections.emptyList(), page, total);
        }
        List<MemberCouponVO> resList = new ArrayList<>();
        Set<Long> memberIds = list.stream().map(it -> it.getMemberId()).collect(Collectors.toSet());
        Map<Long, Member> memberMap = memberMapper.selectList(new QueryWrapper<Member>().in("id", memberIds))
                .stream().collect(Collectors.toMap(it -> it.getId(), it -> it));
        for (MemberCoupon it : list) {
            MemberCouponVO vo = new MemberCouponVO();
            BeanUtils.copyProperties(it, vo);
            Member member = memberMap.get(it.getMemberId());
            if (member != null) {
                vo.setNickname(member.getNickname());
                vo.setPhone(member.getPhoneHidden());
                vo.setAvatar(member.getAvatar());
            }
            resList.add(vo);
        }

        return new PageImpl<>(resList, page, total);
    }

//    /**
//     * 新增用户领券记录
//     *
//     * @param memberCoupon 用户领券记录
//     * @return 结果
//     */
//    public int insert(MemberCoupon memberCoupon) {
//        memberCoupon.setCreateTime(LocalDateTime.now());
//        memberCoupon.setUseStatus(0);
//        memberCoupon.setDeptZbjId(SecurityUtils.getDeptZbjId());
//        return memberCouponMapper.insert(memberCoupon);
//    }

    /**
     * 修改用户领券记录
     *
     * @param memberCoupon 用户领券记录
     * @return 结果
     */
    public int update(MemberCoupon memberCoupon) {
        return memberCouponMapper.updateById(memberCoupon);
    }

    /**
     * 删除用户领券记录信息
     *
     * @param id 用户领券记录主键
     * @return 结果
     */
    public int deleteById(Long id) {
        return memberCouponMapper.deleteById(id);
    }
    

	public List<CouponCategoryDTO> selectListGrepByH5(MemberCouponQuery query) {
        QueryWrapper<MemberCoupon> qw = new QueryWrapper<>();
        qw.eq("member_id", query.getMemberId());
        Long couponCategoryId = query.getCouponCategoryId();
        if(couponCategoryId!=null) {
            qw.eq("coupon_category_id", couponCategoryId);
        }
        qw.select("coupon_category_id as couponCategoryId, count(*) as memberId");
        LocalDateTime now = LocalDateTime.now();
        if (query.getType() != null) {
            switch (query.getType()) {
                case 1:
                    //已领取
                    qw.eq("use_status", 0)
                            .ge("end_time", now)
                            .le("begin_time", now);
                    break;
                case 2:
                    //已使用
                    qw.eq("use_status", 1);
                    break;
                case 3:
                    //已过期
                    qw.eq("use_status", 0);
                    qw.and(it -> it.le("end_time", now).or().ge("begin_time", now));
                    break;
                default:
                    break;
            }
        }
        qw.groupBy("couponCategoryId");
        qw.orderByAsc("couponCategoryId");
        List<MemberCoupon> list = memberCouponMapper.selectList(qw);
        List<CouponCategoryDTO> retList = new ArrayList<CouponCategoryDTO>();
        if(list!=null && list.size()>0){
        	List<Long> ids = new ArrayList<Long>();
        	Map<Long, Long>  map = new HashMap<Long, Long>(); 
        	for (MemberCoupon memberCoupon : list) {
        		ids.add(memberCoupon.getCouponCategoryId());
        		map.put(memberCoupon.getCouponCategoryId(), memberCoupon.getMemberId());
			}
        	List<CouponCategory> ccList =  couponCategoryMapper.selectBatchIds(ids);
        	if(ccList!=null && ccList.size()>0) {
        		for (CouponCategory source : ccList) {
        			CouponCategoryDTO ccd = couponCategoryConvert.do2dto(source);
        			ccd.setSl(map.get(source.getId()));
        			retList.add(ccd);
				}
        	}
        }
        
        return retList;
    }
	

    public Page<MemberCoupon> selectListByH5(MemberCouponQuery query, Pageable page) {
    	String px = "create_time desc";
    	if (query.getType() != null && query.getType()==2) {
    		px = "use_time desc";
        }
        PageHelper.startPage(page.getPageNumber() + 1, page.getPageSize(),px);
        QueryWrapper<MemberCoupon> qw = new QueryWrapper<>();
        qw.eq("member_id", SecurityUtil.getLocalMember().getId());
        Long couponActivityId = query.getCouponActivityId();
        if(couponActivityId!=null) {
            qw.eq("coupon_activity_id", couponActivityId);
        }
        Long couponCategoryId = query.getCouponCategoryId();
        if(couponCategoryId!=null) {
            qw.eq("coupon_category_id", couponCategoryId);
        }
        LocalDateTime now = LocalDateTime.now();
        if (query.getType() != null) {
            switch (query.getType()) {
                case 1:
                    //已领取
                    qw.eq("use_status", 0)
                            .ge("end_time", now)
                            .le("begin_time", now);
                    break;
                case 2:
                    //已使用
                    qw.eq("use_status", 1);
                    break;
                case 3:
                    //已过期
                    qw.eq("use_status", 0);
                    qw.and(it -> it.le("end_time", now).or().ge("begin_time", now));
                    break;
                default:
                    break;
            }
        }
        List<MemberCoupon> list = memberCouponMapper.selectList(qw);
        return new PageImpl<>(list, page, ((com.github.pagehelper.Page) list).getTotal());
    }

    public List<MemberCoupon> getCanUseList(Collection<Product> products) {
        //先获取我的未过期的优惠券
        QueryWrapper<MemberCoupon> queryWrapper = new QueryWrapper<>();
        LocalDateTime now = LocalDateTime.now();
        queryWrapper.eq("member_id", SecurityUtil.getLocalMember().getId())
                .eq("use_status", 0)
                .ge("end_time", now)
                .le("begin_time", now);
        List<MemberCoupon> list = memberCouponMapper.selectList(queryWrapper);
        if (CollectionUtils.isEmpty(list)) {
            return list;
        }
        List<MemberCoupon> matchList = new ArrayList<>();
        list.forEach(item -> {
            if (judgeCouponCanUse(item, products)) {
                matchList.add(item);
            }
        });
        return matchList;
    }

    public Boolean judgeCouponCanUse(MemberCoupon item, Collection<Product> products) {
        //判断是否满足菜品
        if (!Objects.equals(1, item.getUseScope())) {
            List<Long> couponProducts = Arrays.stream(item.getProductIds().split(",")).map(it -> Long.parseLong(it)).collect(Collectors.toList());
            if (Objects.equals(2, item.getUseScope()) && products.stream().noneMatch(it -> couponProducts.contains(it.getId()))) {
                //指定商品
                return false;
            }
            if (Objects.equals(3, item.getUseScope()) && products.stream().anyMatch(it -> couponProducts.contains(it.getId()))) {
                //指定商品不包括
                return false;
            }
        }
        //计算金额是否满足
        if (item.getMinAmount() == null || item.getMinAmount().equals(BigDecimal.ZERO)) {
            //无门槛
            return true;
        }
        if (item.getMinAmount().compareTo(calcMinAmount(products, item)) <= 0) {
            return true;
        }
        return false;
    }

    private BigDecimal calcMinAmount(Collection<Product> products, MemberCoupon coupon) {
        List<Long> ids;
        if (!Objects.equals(1, coupon.getUseScope())) {
            ids = Arrays.stream(coupon.getProductIds().split(",")).map(it -> Long.parseLong(it)).collect(Collectors.toList());
        } else {
            ids = new ArrayList<>();
        }
        switch (coupon.getUseScope()) {
            case 1:
                return products.stream().map(Product::getPrice).reduce(BigDecimal::add).get();
            case 2:
                return products.stream().filter(it -> ids.contains(it.getId())).map(Product::getPrice).reduce(BigDecimal::add).get();
            case 3:
                return products.stream().filter(it -> !ids.contains(it.getId())).map(Product::getPrice).reduce(BigDecimal::add).get();
            default:
                return BigDecimal.ZERO;
        }
    }

    public void updateCouponStatus(Long memberCouponId, Long orderId) {
        UpdateWrapper<MemberCoupon> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", memberCouponId)
                .set("use_status", 1)
                .set("use_time", LocalDateTime.now())
                .set("order_id", orderId);
        memberCouponMapper.update(null, updateWrapper);
    }

    public void backCoupon(List<Long> couponIdList) {
        UpdateWrapper<MemberCoupon> updateWrapper = new UpdateWrapper<>();
        updateWrapper.in("id", couponIdList)
                .set("use_status", 0)
                .set("use_time", null)
                .set("order_id", null);
        memberCouponMapper.update(null, updateWrapper);
    }

    /**
     * 	验证优惠券数量是否足够
     * @param yhqsl 数量
     * @param yhqCategoryid 优惠券分类id
     * @param memberId 会员id
     */
    public List<DyFlqSy> checkCoupon(int yhqsl,Long yhqCategoryid,List<DyFlq> dyflqs,Long memberId) {
    	String flqmc  ="福利券";
    	if(yhqCategoryid!=null) {
        	CouponCategory couponCategory = couponCategoryService.selectCheckById(yhqCategoryid);
    		if(couponCategory!=null) {
    			flqmc  = couponCategory.getTitle();
    		}
    	}
		QueryWrapper<MemberCoupon> queryWrapper = new QueryWrapper<>();
        LocalDateTime now = LocalDateTime.now();
        queryWrapper
        		.eq("coupon_category_id", yhqCategoryid)
        		.eq("member_id", memberId)
                .eq("use_status", 0)
                .ge("end_time", now)
                .le("begin_time", now)
                .orderByAsc("begin_time");
        int num = memberCouponMapper.selectCount(queryWrapper);
        List<DyFlqSy> retFlq = new ArrayList<DyFlqSy>();
        retFlq.add(new DyFlqSy(yhqCategoryid, flqmc, num));
        if(num < yhqsl) {
        	if(dyflqs==null) {
                throw new RuntimeException(flqmc+"数量不足，当前"+flqmc+"数量："+num+"张");
        	}
        	int dyqNum = getDyflqNum(dyflqs, memberId);
        	if(dyqNum==0) {
                throw new RuntimeException(flqmc+"数量不足，当前"+flqmc+"数量："+num+"张");
        	}
        	int sumNum = num + dyqNum;
        	String bhflqmc = "替用福利券";
        	if(dyflqs!=null && dyflqs.size()>0) {
        		DyFlq dyFlq = dyflqs.get(0);
            	bhflqmc = dyFlq.getName();
                retFlq.add(new DyFlqSy(dyFlq.getId(), bhflqmc, dyqNum));
        	}
        	if(sumNum < yhqsl) {
                throw new RuntimeException(flqmc+"："+num+"张,"+bhflqmc+"："+dyqNum+"张，共："+sumNum+"数量不足");
        	}
        }
        return retFlq;
	}
    
    
    
    public int getDyflqNum(List<DyFlq> dyflqs,Long memberId) {
    	if(dyflqs!=null && dyflqs.size()>0) {
    		List<Long> ids = new ArrayList<Long>();
    		for (DyFlq dyFlq : dyflqs) {
    			ids.add(dyFlq.getId());
			}
    		QueryWrapper<MemberCoupon> queryWrapper = new QueryWrapper<>();
            LocalDateTime now = LocalDateTime.now();
            queryWrapper
            		.in("coupon_category_id", ids)
            		.eq("member_id", memberId)
                    .eq("use_status", 0)
                    .ge("end_time", now)
                    .le("begin_time", now)
                    .orderByAsc("begin_time");
            return memberCouponMapper.selectCount(queryWrapper);
    	}
		return 0;
    }
    
    
    public List<MemberCoupon> getDyflqList(List<DyFlq> dyflqs,Long memberId,int num) {
        PageHelper.startPage(1, num);
    	List<MemberCoupon> list = null;
    	if(dyflqs!=null && dyflqs.size()>0) {
    		List<Long> ids = new ArrayList<Long>();
    		for (DyFlq dyFlq : dyflqs) {
    			ids.add(dyFlq.getId());
			}
    		QueryWrapper<MemberCoupon> queryWrapper = new QueryWrapper<>();
            LocalDateTime now = LocalDateTime.now();
            queryWrapper
            		.in("coupon_category_id", ids)
            		.eq("member_id", memberId)
                    .eq("use_status", 0)
                    .ge("end_time", now)
                    .le("begin_time", now)
                    .orderByAsc("begin_time");
            return memberCouponMapper.selectList(queryWrapper);
    	}
		return list;
    }
    
    
    /**
     * 	验证优惠券数量是否足够
     * @param yhqsl 数量
     * @param yhqCategoryid 优惠券分类id
     * @param memberId 会员id
     */
    public int getFlqNum(Long yhqCategoryid,Long memberId) {
		QueryWrapper<MemberCoupon> queryWrapper = new QueryWrapper<>();
        LocalDateTime now = LocalDateTime.now();
        queryWrapper
        		.eq("coupon_category_id", yhqCategoryid)
        		.eq("member_id", memberId)
                .eq("use_status", 0)
                .ge("end_time", now)
                .le("begin_time", now)
                .orderByAsc("begin_time");
        int num = memberCouponMapper.selectCount(queryWrapper);
		return num;
       
	}
    
    
    
	public Boolean exchangeCouponByH5(CouponActivitySy query) {
        PageHelper.startPage(1, query.getSl());
		QueryWrapper<MemberCoupon> queryWrapper = new QueryWrapper<>();
        LocalDateTime now = LocalDateTime.now();
        queryWrapper
        		.eq("coupon_category_id", query.getCategoryid())
        		.eq("member_id", query.getMemberId())
                .eq("use_status", 0)
                .ge("end_time", now)
                .le("begin_time", now)
                .orderByAsc("begin_time");
        List<MemberCoupon> list = memberCouponMapper.selectList(queryWrapper);
        if(list.size() != query.getSl()) {
            throw new RuntimeException("优惠券数量不足");
        }
        List<Long> ids = new ArrayList<Long>();
        for (MemberCoupon mc : list) {
        	ids.add(mc.getId());
		}

        
        
        Member member = (Member) LocalDataUtil.getVar(Constants.MEMBER_INFO);

        
        UpdateWrapper<MemberCoupon> updateWrapper = new UpdateWrapper<>();
        updateWrapper.in("id", ids)
			         .eq("coupon_category_id", query.getCategoryid())
					 .eq("member_id", query.getMemberId())
			         .eq("use_status", 0)
			         .ge("end_time", now)
			         .le("begin_time", now)
                .set("use_status", 1)
                .set("use_time", now)
                .set("hxbz", query.getHxbz())
                .set("dept_dp_id", member.getDeptDpId())
		        .set("dept_tz_id", member.getDeptTzId())
		        .set("dept_zbj_id", member.getDeptZbjId())
        		.set("dp_member_id", member.getId());

        int uSl = memberCouponMapper.update(null, updateWrapper);
        if(uSl!=query.getSl()) {
            throw new RuntimeException("优惠券数量不足");
        }
		return true;
	}
	
	
	public Boolean exchangeCouponByAdmin(CouponActivitySy query) {
        PageHelper.startPage(1, query.getSl());
		QueryWrapper<MemberCoupon> queryWrapper = new QueryWrapper<>();
        LocalDateTime now = LocalDateTime.now();
        queryWrapper
        		.eq("coupon_category_id", query.getCategoryid())
        		.eq("member_id", query.getMemberId())
                .eq("use_status", 0)
                .ge("end_time", now)
                .le("begin_time", now)
                .orderByAsc("begin_time");
        List<MemberCoupon> list = memberCouponMapper.selectList(queryWrapper);
        if(list.size() != query.getSl()) {
            throw new RuntimeException("优惠券数量不足");
        }
        List<Long> ids = new ArrayList<Long>();
        for (MemberCoupon mc : list) {
        	ids.add(mc.getId());
		}

        
        
        Member member = memberMapper.selectById(query.getMemberId());

       
        UpdateWrapper<MemberCoupon> updateWrapper = new UpdateWrapper<>();
        updateWrapper.in("id", ids)
			         .eq("coupon_category_id", query.getCategoryid())
					 .eq("member_id", query.getMemberId())
			         .eq("use_status", 0)
			         .ge("end_time", now)
			         .le("begin_time", now)
                .set("use_status", 1)
                .set("use_time", now)
                .set("hxbz", "后台管理员核销")
                .set("dept_dp_id", member.getDeptDpId())
		        .set("dept_tz_id", member.getDeptTzId())
		        .set("dept_zbj_id", member.getDeptZbjId());

        int uSl = memberCouponMapper.update(null, updateWrapper);
        if(uSl!=query.getSl()) {
            throw new RuntimeException("优惠券数量不足");
        }
		return true;
	}
	
 

	public List<DyFlqSy> orderSubmit(Long orderId, int dhCouponCategoryNum, Long dhCouponCategoryId,List<DyFlq> dyflqs, Long memberId) {
		if(dhCouponCategoryNum == 0) {
	         throw new RuntimeException("智能拦截，福利券兑换数量未设置!");
	    }
	 	String flqmc  ="福利券";
    	if(dhCouponCategoryId!=null) {
        	CouponCategory couponCategory = couponCategoryService.selectCheckById(dhCouponCategoryId);
    		if(couponCategory!=null) {
    			flqmc  = couponCategory.getTitle();
    		}
    	}
    	
		PageHelper.startPage(1, dhCouponCategoryNum);
		QueryWrapper<MemberCoupon> queryWrapper = new QueryWrapper<>();
        LocalDateTime now = LocalDateTime.now();
        queryWrapper
        		.eq("coupon_category_id", dhCouponCategoryId)
        		.eq("member_id", memberId)
                .eq("use_status", 0)
                .ge("end_time", now)
                .le("begin_time", now)
                .orderByAsc("begin_time");
        List<MemberCoupon> list = memberCouponMapper.selectList(queryWrapper);
        List<MemberCoupon> tyqList = null;
        if(list.size() != dhCouponCategoryNum) {
        	if(dyflqs==null) {
                throw new RuntimeException("福利券数量不足");
        	}
        	int dyqNum = dhCouponCategoryNum-list.size();
        	tyqList = this.getDyflqList(dyflqs, memberId, dyqNum);
        	if(tyqList==null || tyqList.size() != dyqNum){
        		 throw new RuntimeException("福利券数量不足");
        	}
        }
       
        List<Long> ids = new ArrayList<Long>();
        for (MemberCoupon mc : list) {
        	ids.add(mc.getId());
		}
        int uSl = 0;
        if(list.size() > 0) {
        	UpdateWrapper<MemberCoupon> updateWrapper = new UpdateWrapper<>();
            updateWrapper.in("id", ids)
    			         .eq("coupon_category_id", dhCouponCategoryId)
    					 .eq("member_id", memberId)
    			         .eq("use_status", 0)
    			         .ge("end_time", now)
    			         .le("begin_time", now)
                    .set("use_status", 1)
                    .set("use_time", now)
                    .set("order_id", orderId)
                    .set("hxbz", "商品兑换核销");
             uSl = memberCouponMapper.update(null, updateWrapper);
        }
        
        
        List<DyFlqSy> retFlq = new ArrayList<DyFlqSy>();
        retFlq.add(new DyFlqSy(dhCouponCategoryId, flqmc, uSl));
        
        if(uSl==dhCouponCategoryNum) {
        	return retFlq;
        }
	   	if(tyqList==null || tyqList.size() == 0){//没有替用券
	   		 if(uSl!=dhCouponCategoryNum) {
	             throw new RuntimeException("福利券数量不足");
	         }
	   	}
	   	 
	   	 
	   //没有替用券
        List<Long> iddys = new ArrayList<Long>();
        for (MemberCoupon mc : tyqList) {
        	iddys.add(mc.getId());
		}
        
        UpdateWrapper<MemberCoupon> updateWrapperTyq = new UpdateWrapper<>();
        updateWrapperTyq.in("id", iddys)
					 .eq("member_id", memberId)
			         .eq("use_status", 0)
			         .ge("end_time", now)
			         .le("begin_time", now)
                .set("use_status", 1)
                .set("use_time", now)
                .set("order_id", orderId)
                .set("hxbz", "商品兑换核销-替用");
        int udySl = memberCouponMapper.update(null, updateWrapperTyq);
        
        if((uSl+udySl)!=dhCouponCategoryNum) {
            throw new RuntimeException("福利券数量不足");
        }
        
      	String bhflqmc = "替用福利券";
    	if(dyflqs!=null && dyflqs.size()>0) {
    		DyFlq dyFlq = dyflqs.get(0);
        	bhflqmc = dyFlq.getName();
            retFlq.add(new DyFlqSy(dyFlq.getId(), bhflqmc, udySl));
    	}
        return retFlq;
	}

}
